package com.banciyuan.bcywebview.biz.circles.discover.tagnav;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.TagApi;
import com.banciyuan.bcywebview.base.fragment.BaseFragment;
import com.banciyuan.bcywebview.base.helper.ProgressbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.string.StringUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.CategroyTag;
import de.greenrobot.daoexample.model.FollowTag;

/**
 * Created by squall on 2017/3/20.
 */

public class DiscoverTagNavFragment extends BaseFragment {

    private ListView left_nav;
    private RecyclerView right_container;
    private DiscoverTagNavLeftAdapter discoverTagNavLeftAdapter;
    private DiscoverTagNavRightAdapter discoverTagNavRightAdapter;
    private List<FollowTag> flist = new ArrayList<>();
    private List<FollowTag> rightList = new ArrayList<>();
    private RequestQueue queue;
    private GridLayoutManager gridLayoutManager;
    private ProgressbarHelper mProgressbarHelper;

    private List<CategroyTag> categroyTags = new ArrayList<>();
    private String tag_type;
    private int jump_index;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View viewRoot = inflater.inflate(R.layout.activity_discover_tag, null);
        initArgs();
        initProgressbar(viewRoot);
        initUi(viewRoot);
        getTypeTag();
        return viewRoot;
    }

    @Override
    protected void initArgs() {
        queue = VolleyQueue.getRquest(getActivity());
        if (getArguments() != null) {
            tag_type = getArguments().getString("tag_type");
        }
    }

    @Override
    protected void initProgressbar(View rootview) {
        mProgressbarHelper = new ProgressbarHelper(rootview);
        mProgressbarHelper.setActionCallbacks(new ProgressbarHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initUi(View rootview) {
        left_nav = (ListView) rootview.findViewById(R.id.left_nav);
        right_container = (RecyclerView) rootview.findViewById(R.id.right_container);

        discoverTagNavRightAdapter = new DiscoverTagNavRightAdapter(getActivity(), rightList);
        gridLayoutManager = new GridLayoutManager(getActivity(), 2);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (discoverTagNavRightAdapter.getItemViewType(position) == 0) {
                    return 2;
                } else if (discoverTagNavRightAdapter.getItemViewType(position) == 2) {
                    return 2;
                } else if (discoverTagNavRightAdapter.getItemViewType(position) == -1) {
                    return 2;
                } else {
                    return 1;
                }
            }
        });
        RecyclerView.ItemAnimator animator = right_container.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        right_container.addItemDecoration(new CircleItemDecoration(getActivity()));
        right_container.setLayoutManager(gridLayoutManager);
        right_container.setAdapter(discoverTagNavRightAdapter);
    }

    @Override
    protected void initData() {
        String url = HttpUtils.BASE_URL + TagApi.getHotSubFollow();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(getActivity()).getToken()));
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    Gson gson = new Gson();
                    JSONObject jsonObject = new JSONObject(response);
                    flist = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<FollowTag>>() {
                    }.getType());
                    renderData();
                } catch (Exception e) {
                    mProgressbarHelper.onFailed();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mProgressbarHelper.onFailed();
            }
        };
        Map<String, String> map = HttpUtils.getData(pairs);
        StringRequestParam stringRequestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        queue.add(stringRequestParam);
    }

    private void getTypeTag() {
        String url = HttpUtils.BASE_URL + TagApi.getTypeTagCircle();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.INDEX_P, String.valueOf(1)));
        pairs.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance().getToken()));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                    try {
                        Gson gson = new Gson();
                        JSONObject jsonObject = new JSONObject(response);
                        categroyTags = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA), new TypeToken<List<CategroyTag>>() {
                        }.getType());
                        initData();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        };

        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSucc, url, getActivity(), map);
        StringRequestParam param = new StringRequestParam(Request.Method.POST, url, map, onSucc, onErrorProxy);
        queue.add(param);
    }

    private void renderData() {
        FollowTag followTag = new FollowTag();
        List<FollowTag> temp = new ArrayList<>();
        for (int i = 0; i < categroyTags.size(); i++) {
            CategroyTag c = categroyTags.get(i);
            FollowTag typeTag = new FollowTag();
            typeTag.setType_name(c.getType_name());
            temp.add(typeTag);
            temp.addAll(c.getTags_data());
        }
        followTag.setTag_name(getString(R.string.hot));
        followTag.setRela_tags(temp);
        flist.add(0, followTag);
        for (int i = 0; i < temp.size(); i++) {
            if (StringUtil.notNullEqual(temp.get(i).getType_name(), tag_type)) {
                jump_index = i;
            }
        }
        discoverTagNavLeftAdapter = new DiscoverTagNavLeftAdapter(getActivity(), flist, new OnDataChange() {
            @Override
            public void onChange(FollowTag f) {
                rightList.clear();
                String name = "";
                if (!StringUtil.notNullEqual(flist.get(flist.indexOf(f)).getTag_name(), getString(R.string.hot))) {
                    rightList.add(flist.get(flist.indexOf(f)));
                    name = flist.get(flist.indexOf(f)).getTag_name();
                } else {
                    name = "";
                }
                rightList.addAll(flist.get(flist.indexOf(f)).getRela_tags());
                if (discoverTagNavRightAdapter != null) {
                    discoverTagNavRightAdapter.setName(name);
                    discoverTagNavRightAdapter.notifyDataSetChanged();
                } else {
                    discoverTagNavRightAdapter = new DiscoverTagNavRightAdapter(getActivity(), rightList);
                    discoverTagNavRightAdapter.setName(name);
                    right_container.setAdapter(discoverTagNavRightAdapter);
                }
                right_container.scrollToPosition(0);
            }
        });
        left_nav.setAdapter(discoverTagNavLeftAdapter);

        if (flist != null && !flist.isEmpty()) {
            rightList.addAll(flist.get(0).getRela_tags());
            discoverTagNavRightAdapter = new DiscoverTagNavRightAdapter(getActivity(), rightList);
            discoverTagNavRightAdapter.setName("");
            right_container.setAdapter(discoverTagNavRightAdapter);
            if (jump_index != 0) {
                GridLayoutManager glm = (GridLayoutManager) right_container.getLayoutManager();
                glm.scrollToPosition(jump_index);
            }
        }
        mProgressbarHelper.onSuccess();
    }

    public interface OnDataChange {
        void onChange(FollowTag name);
    }
}
